import { Message } from 'element-ui'
import { debounce } from '@/utils'

// Simplify add or edit item
export const editFormMixin = {
  props: { value: { type: Boolean, default: false } },
  data() {
    return {
      primaryKey: 'id', // 主健字段。用于判断新增还是编辑
      addApi: '', // 可选。addApi 或 updateApi 必须配置一个
      updateApi: '',
      btnLoading: false,
      form: {},
      formInitVals: {},
      rules: null
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.formInitVals = JSON.parse(JSON.stringify(this.form))
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
  },
  methods: {
    open(item = {}) {
      this.show = true
      this.$nextTick(() => {
        item && Object.keys(this.form).map(k => (this.form[k] = typeof item[k] !== 'undefined' ? item[k] : this.formInitVals[k]))
        this.opened?.(...arguments)
      })
    },
    async onSubmit() {
      if (this.rules) {
        const valid = await this.$refs.form.validate().catch(() => false)
        if (!valid) return
      }

      const { primaryKey, addApi, updateApi } = this
      const opt = { ...this.form }
      const id = opt[primaryKey]
      const submitApi = addApi && updateApi ? (id ? updateApi : addApi) : addApi || updateApi
      if (!submitApi) return Message.error('addApi or updateApi is required')

      !id && delete opt[primaryKey]
      this.btnLoading = true
      const res = await submitApi(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      Message.success(!id ? '新增成功' : '提交成功')
      this.show = false
      this.$emit('ok')
    }
  }
}
